package com.yiyang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yiyang.mapper.BuildingMapper;
import com.yiyang.pojo.Building;
import com.yiyang.pojo.vo.PageResult;
import com.yiyang.pojo.vo.Result;
import com.yiyang.service.BuildingService;
import com.yiyang.utils.BizCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service
public class BuildingServiceImpl extends ServiceImpl<BuildingMapper,Building> implements BuildingService {
    @Autowired
    private BuildingMapper buildingMapper;

    /**
     * 根据id查询信息
     *
     * */
    @Override
    public Result<Building> getBuildingById(Integer id) {
        Building building = this.getById(id);
        if(building != null){
            return Result.success(BizCode.SUCCESS,building);
        }
        return Result.fail(BizCode.FAIL);
    }

    /**
     * 查询全部信息
     * */

    @Override
    public Result<PageResult<List<Building>>> getAllBuilding(Integer currentPage, Integer pageSize, String name) {
        Page<Building> page = new Page<>(currentPage,pageSize);
        // 构建查询条件对象
        QueryWrapper<Building> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(name),"name",name);
        // 执行查询操作，查询完成后在封装到Page<Building> 里面
        this.buildingMapper.selectPage(page,wrapper);
        // page.getRecords() 获取当前查询到的数据
        PageResult<List<Building>> pageResult = new PageResult<>();
        if(page.getRecords().size() > 0){
            pageResult.setData(page.getRecords());
            pageResult.setTotal(page.getTotal());
            return Result.success(BizCode.SUCCESS, pageResult);
        }else {
            return Result.fail(BizCode.FAIL,pageResult);
        }

    }

    /**
     * 添加楼宇信息
     * */

    @Override
    public Result<Void> addBuilding(Building building) {
        // 设置添加楼宇的系统的时间
        building.setCreateTime(new Date());
        // 如果没有传递楼宇的删除状态，则默认未删除
        if(building.getIsDelete() == null){
            building.setIsDelete(0);
        }
        if(this.save(building)){
            return Result.success();
        }
        return Result.fail();
    }

    /**
     * 修改楼宇信息
     * */
    @Override
    public Result<Void> updateBuilding(Building building) {
        if(this.updateById(building)){
            return Result.success();
        }
        return Result.fail();
    }

    /**
     * 删除楼宇信息
     * */
    @Override
    public Result<Void> deleteBuilding(Integer id) {
        if(this.removeById(id)){
            return Result.success();
        }
        return Result.fail();
    }
}
